import styled from '@emotion/styled';
import React, { useEffect } from 'react';
import AgentService from '@/modules/Agent';
import useSyncState from '../hooks/useSyncState';
import { IVariableList } from '@/modules/interface';
import { useTranslation } from 'react-i18next';
import { Tooltip } from 'antd';

const CustomerInforMationContainer = styled.div`
	padding: 0 14px;
`;

const VaribaleName = styled.span``;

const VariableValue = styled.span`
	margin-left: 10px;
`;

const Varibale = styled.p`
	font-size: 12px;
	color: #303030;
	overflow: hidden;
	white-space: nowrap;
	text-overflow: ellipsis;
	margin-bottom: 12px;
	height: 20px;
`;

const Box = styled.div``;

const SplitLine = styled.div`
	width: 100%;
	height: 1px;
	background: #e8e8e8;
	margin: 14px 0;
`;

interface ICustomerVariables {
	role: string;
	value: IVariableList[];
}

const CustomerInforMation = () => {
	const [customerVariables, setCustomerVariables] = useSyncState<ICustomerVariables[]>([]);
	const { t } = useTranslation();
	useEffect(() => {
		if (AgentService.customerVariableList.length === 0) {
			setCustomerVariables([]);
			return;
		}
		let filterData = AgentService.customerVariableList.filter(item => AgentService.configure.ignoreVariableLinkedKeys.indexOf(item.linkedKey as any) === -1);
		console.log('filterData:', filterData);

		let newArray: any = [];
		let keys = filterData.map(item => {
			return item.roleId;
		});
		keys = [...new Set(keys)];
		keys.forEach((id: any, index: number) => {
			const data = filterData.filter(item => item.roleId === id);
			newArray = [...newArray, { role: filterData.find(item => item.roleId === id)?.roleName, value: data }];
			if (index + 1 === keys.length) {
				setCustomerVariables(newArray);
			}
		});
	}, [JSON.stringify(AgentService.customerVariableList)]);

	const showToolTip = (e: any) => {
		if (e.target.clientWidth >= e.target.scrollWidth) {
			e.target.style.pointerEvents = 'none'; // 阻止鼠标事件
		}
	};

	return (
		<CustomerInforMationContainer>
			{customerVariables().map((item, index) => {
				return (
					<div key={index}>
						<Box>
							<Varibale onMouseEnter={showToolTip}>
								<VaribaleName>{t('role')}:</VaribaleName>
								<Tooltip title={item.role}>
									<VariableValue>{item.role ? item.role : '- -'}</VariableValue>
								</Tooltip>
							</Varibale>
							{item.value.map(val => {
								return (
									<Varibale key={val.id} onMouseEnter={showToolTip}>
										<VaribaleName>{val.name}:</VaribaleName>
										<Tooltip title={val.value}>
											<VariableValue>{val.value ? val.value : '- -'}</VariableValue>
										</Tooltip>
									</Varibale>
								);
							})}
						</Box>
						<SplitLine />
					</div>
				);
			})}
		</CustomerInforMationContainer>
	);
};

export default CustomerInforMation;
